prefixes = ['z', 'a', 'f', 'p', 'n', '$\mu$', 'm', 'c', 'd', 
            'da', 'h', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']

factors = [1e-21, 1e-18, 1e-15, 1e-12, 1e-9, 1e-6, 1e-3, 0.01, 0.1,
           10, 100, 1000, 1e6, 1e9, 1e12, 1e15, 1e18, 1e21]

non_metric_units = 'radians deg degrees'.split()

def best_prefix(counts_per, xunits):    
    if not xunits or xunits in non_metric_units:        
        return counts_per, xunits
    
    if xunits.startswith('$\mu$'):
        prefix = '$\mu$'
        unit   = xunits[5:]
    else:                   
        prefix = xunits[0]
        unit   = xunits[1:]

    try:
        prefix_index = prefixes.index(prefix)            
    except ValueError:
        print "Units `{0}' unknown".format(xunits)
        return counts_per, xunits

    while counts_per < 0.999:
        counts_per *= (factors[prefix_index]/factors[prefix_index-1])
        prefix_index -= 1

    while counts_per >= 1000:
        counts_per *= (factors[prefix_index]/factors[prefix_index+1])
        prefix_index += 1

    xunits = prefixes[prefix_index] + unit

    return counts_per, xunits
